<template>
  <a-modal v-model:visible="visible" @ok="submitLink" @cancel="clearSelectStatus" draggable width="80%">
    <template #title> 选择链接 </template>
    <div class="link_wrap">
      <a-tabs v-model:active-key="currentTabs">
        <a-tab-pane key="1" title="App页面">
          <div>
            <dl v-for="(item, index) in appData" :key="index" class="mb-10">
              <dt class="font-weight-500">{{ item.pageName }}</dt>
              <dd>
                <a-button
                  v-for="(val, ind) in item.rules"
                  :key="ind"
                  :type="link == val.rule ? 'primary' : 'dashed'"
                  class="m-5"
                  @click="link = val.rule"
                  >{{ val.name }}</a-button
                >
              </dd>
            </dl>
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" title="小程序">
          <div>
            <dl v-for="(item, index) in appletsData" :key="index" class="mb-10">
              <dt class="font-weight-500">{{ item.pageName }}</dt>
              <dd>
                <a-button
                  v-for="(val, ind) in item.rules"
                  :key="ind"
                  :type="link == val.rule ? 'primary' : 'dashed'"
                  class="m-5"
                  @click="link = val.rule"
                  >{{ val.name }}</a-button
                >
              </dd>
            </dl>
          </div>
        </a-tab-pane>
        <a-tab-pane key="3" title="商品">
          <a-form label-align="right" auto-label-width :model="goodsDetailsParams" size="small" class="form my-10">
            <a-row :gutter="16" wrap>
              <a-col :xs="12" :md="8" :lg="6" :xl="4" :xxl="4">
                <a-form-item field="sourceType" hide-label>
                  <a-select
                    :style="{ width: '160px' }"
                    placeholder="请选择分类"
                    v-model="goodsDetailsParams.sourceType"
                    @change="handleChangeplatforms"
                    :trigger-props="{ autoFitPopupMinWidth: true }"
                  >
                    <a-option v-for="item in platformList" :key="item.sourceType" :value="item.sourceType">{{
                      item.title
                    }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col
                :xs="12"
                :md="8"
                :lg="6"
                :xl="4"
                :xxl="4"
                :key="index"
                v-for="(item, index) in showInputParams && showInputParams.params"
              >
                <a-form-item :field="item.code" hide-label>
                  <a-input v-model="goodsDetailsParams[item.code]" :placeholder="`请输入` + item.name" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-button shape="round" size="small" @click="getGoodsDetails"
                  ><template #icon> <icon-plus /> </template>获取商品</a-button
                >
              </a-col>
            </a-row>
          </a-form>
          <GiTable
            row-key="id"
            id="appDecorationEditLink1"
            v-model:columns="columns2"
            :loading="loading"
            :data="goodsDetailsData"
            :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
            :scrollbar="true"
            :row-selection="{ type: 'checkbox', showCheckedAll: true }"
            @refresh="getGoodsDetails"
            :flex="false"
          >
            <template #picUrl="{ record }">
              <ImgHoverPreview :width="70" :url="record.picUrl" />
            </template>
            <template #action="{ record }">
              <a-switch :checked-value="1" :unchecked-value="0" :before-change="handleChangeStatus">
                <template #checked-icon>
                  <icon-check />
                </template>
                <template #unchecked-icon>
                  <icon-close />
                </template>
              </a-switch>
            </template>
          </GiTable>
        </a-tab-pane>
        <a-tab-pane key="4" title="文章">
          <a-form label-align="right" auto-label-width :model="searchArticleParams" size="small" class="form my-10">
            <a-row :gutter="16" wrap>
              <a-col :xs="12" :md="8" :lg="6" :xl="4" :xxl="4">
                <a-form-item field="categoryId" hide-label>
                  <a-cascader
                    v-model="searchArticleParams.categoryId"
                    :options="categoryTreeArr"
                    expand-trigger="hover"
                    :style="{ width: '220px' }"
                    placeholder="请选择"
                    @change="onChangeArticleType"
                    allow-clear
                    class="mr-5"
                  />
                </a-form-item>
              </a-col>
              <a-col :xs="12" :md="8" :lg="6" :xl="4" :xxl="6">
                <a-form-item field="date" hide-label>
                  <a-range-picker
                    @change="onChangeArticleDate"
                    format="YYYY-MM-DD HH:mm:ss"
                    :time-picker-props="{ defaultValue: ['00:00:00', '23:59:59'] }"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :xs="12" :md="8" :lg="6" :xl="4" :xxl="4">
                <a-form-item field="keyword" hide-label>
                  <a-input-search
                    placeholder="请输入文章关键字"
                    v-model="searchArticleParams.keyword"
                    style="width: 200px"
                    @search="getTableData"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <GiTable
            row-key="id"
            id="appDecorationEditLink2"
            v-model:columns="articleColumns"
            :loading="loading"
            :data="articleDataArr"
            :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
            :scrollbar="true"
            :row-selection="{ type: 'checkbox', showCheckedAll: true }"
            :pagination="pagination"
            @refresh="getTableData"
            :flex="false"
          >
            <template #action="{ record }">
              <a-switch
                :checked-value="true"
                :unchecked-value="false"
                @change="onChangeArticle($event, record)"
                :model-value="articleCheckedId == record.id"
              >
                <template #checked-icon>
                  <icon-check />
                </template>
                <template #unchecked-icon>
                  <icon-close />
                </template>
              </a-switch>
            </template>
          </GiTable>
        </a-tab-pane>
        <a-tab-pane key="5" title="自定义跳转">
          <a-button-group type="primary" class="mt-5">
            <a-button
              v-for="(item, index) in customWebRules"
              :key="index"
              :type="webType == index ? 'primary' : 'outline'"
              @click="changeCustomWebRulesBtn(item, index)"
              class="mb-5"
            >
              {{ item && item.pageName }}
            </a-button>
          </a-button-group>
          <div class="flex flex-a-c mt-20">
            <div class="mr-10">链接地址:</div>
            <a-input
              placeholder="请填写跳转网址带http://"
              v-model="appViewPath"
              v-if="customWebRules.length && customWebRules[webType].pageCode == 'app_view'"
              class="flex-1"
            />
            <a-input
              v-else-if="customWebRules.length && customWebRules[webType].pageCode == 'tip'"
              class="flex-1"
              placeholder="请填写tip跳转网址带http://"
              v-model="tipTitle"
              style="width: 500px"
            />
            <a-input-group
              v-else-if="customWebRules.length && customWebRules[webType].pageCode == 'platform_view'"
              class="flex-1"
            >
              <a-select
                :style="{ width: '160px' }"
                placeholder="选择平台"
                v-model="platformParams.sourceType"
                :trigger-props="{ autoFitPopupMinWidth: true }"
              >
                <a-option v-for="item in platformList" :key="item.sourceType" :value="item.sourceType">{{
                  item.title
                }}</a-option>
              </a-select>
              <a-input placeholder="请填写跳转内部web网址带http://" v-model="platformParams.path" />
            </a-input-group>
            <a-input-group
              v-else-if="customWebRules.length && customWebRules[webType].pageCode == 'web_view'"
              class="flex-1"
            >
              <a-select
                :style="{ width: '160px' }"
                placeholder="选择平台"
                v-model="webViewParams.sourceType"
                :trigger-props="{ autoFitPopupMinWidth: true }"
              >
                <a-option v-for="item in platformList" :key="item.sourceType" :value="item.sourceType">{{
                  item.title
                }}</a-option>
              </a-select>
              <a-input class="flex-1" placeholder="请填写外部web跳转网址带http://" v-model="webViewParams.path" />
            </a-input-group>
          </div>
          <a-row class="mt-30 mb-10">
            <a-checkbox v-model="needLogin" class="mr-20"> 是否需要登录 </a-checkbox>
            <a-checkbox v-model="needRecord"> 是否需要授权 </a-checkbox>
          </a-row>
        </a-tab-pane>
        <a-tab-pane key="6" title="第三方APP">
          <a-form label-align="right" auto-label-width :model="otherAppParams" size="small" class="form my-10">
            <a-row :gutter="16" wrap>
              <a-col :span="24">
                <a-form-item field="sourceType" label="App">
                  <a-select
                    :style="{ width: '160px' }"
                    placeholder="请选择平台"
                    v-model="otherAppParams.sourceType"
                    :trigger-props="{ autoFitPopupMinWidth: true }"
                  >
                    <a-option v-for="item in platformList" :key="item.sourceType" :value="item.sourceType">{{
                      item.title
                    }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item field="sourceType" label="活动id或地址">
                  <a-input placeholder="请填写联盟活动id或地址" v-model="otherAppParams.path"></a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-modal>
</template>
<script setup>
import {
  linkRulePlatforms,
  linkRuleGoods,
  linkRuleApp,
  linkRuleArticle,
  articleCategoryTree,
  articleSearch,
  linkRuleApplets,
  linkRuleOtherApp,
  linkRuleWeb,
  goodsDetails
  // linkRuleGoods
} from '@/apis'
import { usePlatform } from '@/hooks/app'
import { Message } from '@arco-design/web-vue'
import { usePagination } from '@/hooks'
const { pagination, setTotal } = usePagination(() => getTableData(), { defaultPageSize: 10 })
const props = defineProps({
  isIntegral: {
    default: false,
    type: Boolean
  } // 非资源位模块备用
})
const currentTabs = ref('1')
const visible = ref(false)
const menuList = [
  { title: 'App页面' },
  { title: '小程序' },
  { title: '商品' },
  { title: '文章' },
  { title: '自定义跳转' },
  { title: '第三方APP' }
]
const appData = ref([])
const appletsData = ref([])
const loading = ref(false)
const goodsDetailsData = ref([])
const goodsDetailsParams = reactive({
  sourceType: '',
  goodsId: '',
  couponUrl: '',
  supplierCode: '',
  page: 0
})
const columns2 = [
  {
    title: '商品名称',
    width: 100,
    align: 'center',
    render: (data) => {
      const text = data.record.title
      return text || '--'
    }
  },
  {
    title: '店铺类型',
    width: 50,
    align: 'center',
    render: (data) => {
      const text = data.record.shopType
      return text || '--'
    }
  },
  {
    title: '券后价',
    width: 50,
    align: 'center',
    render: (data) => {
      const text = data.record.actualPrice
      return text || '--'
    }
  },
  {
    title: '券额',
    width: 50,
    align: 'center',
    render: (data) => {
      const text = data.record.couponPrice
      return text || '--'
    }
  },
  {
    title: '商品图片',
    width: 50,
    align: 'center',
    slotName: 'picUrl'
  },
  {
    title: '选择',
    width: 50,
    align: 'center',
    fixed: 'right',
    slotName: 'action'
  }
]

const articleColumns = [
  //文章列表
  {
    title: '标题',
    align: 'center',
    width: 120,
    render: (data) => {
      const text = data.record.title
      return text || '--'
    }
  },
  {
    title: '浏览量',
    align: 'center',
    width: 100,
    render: (data) => {
      const text = data.record.chickNum
      return text || '--'
    },
    dataIndex: 'chickNum',
    sortable: {
      sorter: true,
      sortDirections: ['descend', 'ascend']
    }
  },
  {
    title: '分享量',
    align: 'center',
    width: 100,
    render: (data) => {
      const text = data.record.shareNum
      return text || '--'
    },
    dataIndex: 'shareNum',
    sortable: {
      sorter: true,
      sortDirections: ['descend', 'ascend']
    }
  },
  {
    title: '发布时间',
    key: 'publishedAt',
    align: 'center',
    width: 120,
    render: (data) => {
      const text = data.record.publishedAt
      return text || '--'
    },
    dataIndex: 'publishedAt',
    sortable: {
      sorter: true,
      sortDirections: ['descend', 'ascend']
    }
  },
  {
    title: '选择',
    slotName: 'action',
    align: 'center',
    width: 100,
    fixed: 'right'
  }
]

const selectGoodsRule = ref('') // 商品
const goodsRules = ref([])
const selectGoodsParams = reactive({})
const showInputParams = ref({ params: [] })

const categoryTreeArr = ref([]) // 文章树
const articleDataArr = ref([]) // 文章表格数据
const searchArticleParams = reactive({
  keyword: '',
  // date: '',
  categoryId: '',
  page: 1,
  pageSize: 10,
  startAt: '',
  endAt: ''
}) // 文章搜索

/* 获得平台分类 */
const { platformList, getPlatformList } = usePlatform()

/* 获得APP页面 */
const getLinkRuleApp = async () => {
  const res = await linkRuleApp()
  appData.value = res.data
}
/* 获得小程序页面 */
const getLinkRuleApplets = async () => {
  const res = await linkRuleApplets()
  appletsData.value = res.data
}

/* 获得商品详情 */
const getGoodsDetails = async () => {
  try {
    loading.value = true
    const res = await goodsDetails(goodsDetailsParams)
    goodsDetailsData.value = [res.data]
  } finally {
    loading.value = false
  }
}

// 选择 商品链接
const handleChangeStatus = async (value) => {
  if (value) {
    // 拼接商品链接
    let goodsId = ''
    let sourceType = ''
    const isPush = 1
    if (props.isIntegral) {
      const goodsItem = goodsDetailsData.value[0]
      sourceType = goodsItem.sourceType
      goodsId = goodsItem.goodsId
    } else {
      const goodsItem = goodsDetailsData.value[0]
      goodsId = goodsItem.goodsId
      sourceType = goodsItem.sourceType
    }
    // const goodsItem = goodsDetailsData.value[0]
    // const sourceType = goodsItem.sourceType
    // const goodsId = goodsItem.goodsId
    // const goodsId2 = goodsItem.goodsId2 || ''
    selectGoodsRule.value = goodsRules.value[0].rule + orderList({ goodsId, sourceType, isPush }) //链接拼接参数
  }
}
const getLinkRuleGoods = async () => {
  const res = await linkRuleGoods({})
  goodsRules.value = res.data
}

//跳转规则选择商品分类
const handleChangeplatforms = (value) => {
  selectGoodsParams.value = {}
  selectGoodsParams.sourceType = value
  if (goodsRules.length < value) {
    showInputParams.params = []
  } else {
    showInputParams.value = goodsRules.value.find((el) => {
      return el.sourceType == value
    })
  }
}
//对象参数序列化
const orderList = (params) => {
  let paramsData = []
  for (const Key in params) {
    paramsData.push(`${Key}=${params[Key]}`)
  }
  paramsData = paramsData.join('&')
  return '?' + paramsData
}

const getCateTree = async () => {
  await articleCategoryTree().then((res) => {
    //文章分类树
    if (res.code == 200) {
      categoryTreeArr.value = res.data
    }
  })
}

const onChangeArticleType = (value) => {
  //选择文章分类
  searchArticleParams.categoryId = value
}
const onChangeArticleDate = (date) => {
  //选择文章时间
  searchArticleParams.startAt = date[0]
  searchArticleParams.endAt = date[1]
}

const getTableData = async () => {
  //搜索文章
  try {
    loading.value = true
    searchArticleParams.page = pagination.current
    const res = await articleSearch(searchArticleParams)
    articleDataArr.value = res.data.data
    setTotal(res?.data?.meta?.pagination?.total || 0)
  } finally {
    loading.value = false
  }
}
// 表格页码改变
const changeCurrent = (e) => {
  pagination.current_page = searchArticleParams.page = e
  getTableData()
}
const articleCheckedId = ref(0)
const articleCheckedTitle = ref('')
const onChangeArticle = (e, record) => {
  articleCheckedId.value = record.id
  articleCheckedTitle.value = record.title
}

/* 自定义跳转 */
const webType = ref(0)
const customWebRules = ref([])
const appViewPath = ref('')
const tipTitle = ref('')
const platformParams = ref({
  sourceType: '',
  path: ''
})
const webViewParams = ref({
  sourceType: '',
  path: ''
})
const needLogin = ref(true)
const needRecord = ref(true)

const otherAppParams = ref({
  sourceType: '',
  path: ''
}) // 第三方地址

const getLinkRuleWeb = async () => {
  await linkRuleWeb().then((res) => {
    customWebRules.value = res.data
    // webType.value = res.data[0].pageCode
  })
}
const changeCustomWebRulesBtn = (item, index) => {
  webType.value = index
}

const link = ref('')
const emit = defineEmits(['click', 'cancel'])
/* 清空 */
const clearSelectStatus = () => {
  link.value = ''
  appViewPath.value = ''
  tipTitle.value = ''

  otherAppParams.value.sourceType = ''
  otherAppParams.value.path = ''

  webViewParams.value.sourceType = ''
  webViewParams.value.path = ''

  platformParams.value.sourceType = ''
  platformParams.value.path = ''
  emit('cancel')
}
const submitLink = () => {
  //提交链接   1 app页面   2小程序 3商品  4文章  5自定义  6第三方
  if (currentTabs.value == 1) {
    // link.value = this.selectAppRule
  } else if (currentTabs.value == 2) {
    // link.value = this.selectAppLetsRule
  } else if (currentTabs.value == 3) {
    link.value = selectGoodsRule.value
  } else if (currentTabs.value == 4) {
    link.value =
      'msmm://appView?path=http://h5.maishou88.com/systemNotice?id=' +
      articleCheckedId.value +
      '&title=' +
      articleCheckedTitle.value
  } else if (currentTabs.value == 5) {
    const linkstr = ref('&needLogin=' + (needLogin.value ? 1 : 0) + '&needRecord=' + (needRecord.value ? 1 : 0))
    if (customWebRules.value[webType.value].pageCode == 'app_view') {
      link.value = 'msmm://appView?path=' + appViewPath.value + linkstr.value
    } else if (customWebRules.value[webType.value].pageCode == 'platform_view') {
      link.value =
        'msmm://platformView' +
        orderList({ path: platformParams.value.path, sourceType: platformParams.value.sourceType }) +
        linkstr.value
    } else if (customWebRules.value[webType.value].pageCode == 'web_view') {
      link.value =
        'msmm://webView' +
        orderList({ path: webViewParams.value.path, sourceType: webViewParams.value.sourceType }) +
        linkstr.value
    } else if (customWebRules.value[webType.value].pageCode == 'tip') {
      link.value = 'msmm://tip?title=' + tipTitle.value + linkstr.value
    }
  } else if (currentTabs.value == 6) {
    link.value =
      'msmm://otherAppPage' +
      orderList({ path: otherAppParams.value.path, sourceType: otherAppParams.value.sourceType }) //第三方链接
  }
  visible.value = false
  emit('click', link.value)
}

getPlatformList()
getLinkRuleApp()
getLinkRuleApplets()
getLinkRuleGoods()
getCateTree()
getLinkRuleWeb()
const changeLink = () => {
  visible.value = true
}
defineExpose({ changeLink })
</script>
